import WKT from 'ol/format/WKT'
import GeoJSON from 'ol/format/GeoJSON'

function getGUID() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4()
}

//根据中心点和半径获取圆的坐标
function convertCircleTo360Latlngs(origin, radius) {
  var EARTH_RADIUS = 6378.14 * 1000
  var lat = (origin.lat * Math.PI) / 180
  var lon = (origin.lng * Math.PI) / 180
  var d = parseFloat(radius) / EARTH_RADIUS
  var Latlngs = new Array()
  for (let i = 0; i <= 360; i++) {
    var loc = []
    var bearing = (i * Math.PI) / 180
    loc[0] = Math.asin(
      Math.sin(lat) * Math.cos(d) + Math.cos(lat) * Math.sin(d) * Math.cos(bearing),
    )
    loc[1] =
      ((lon +
        Math.atan2(
          Math.sin(bearing) * Math.sin(d) * Math.cos(lat),
          Math.cos(d) - Math.sin(lat) * Math.sin(loc[0]),
        )) *
        180) /
      Math.PI
    loc[0] = (loc[0] * 180) / Math.PI
    Latlngs.push(loc)
  }
  return Latlngs
}
//时间戳转换方法    date:时间戳数字
function add0(m) {
  return m < 10 ? '0' + m : m
}
function formatDate(shijianchuo) {
  var time = new Date(shijianchuo)
  var y = time.getFullYear()
  var m = time.getMonth() + 1
  var d = time.getDate()
  var h = time.getHours()
  var mm = time.getMinutes()
  var s = time.getSeconds()
  return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s)
}

function geoJsonToWktStr(geoJson) {
  let wkt = new WKT()
  let g = new GeoJSON().readGeometry(geoJson)
  return wkt.writeGeometry(g)
}

function wktStrToGeoJson(wktText) {
  let wkt = new WKT().readGeometry(wktText)
  let geoJson = new GeoJSON()
  return geoJson.writeGeometry(wkt)
}

export { convertCircleTo360Latlngs, formatDate, getGUID, geoJsonToWktStr, wktStrToGeoJson }
